package com.lagou.consumer;

import com.lagou.RpcDecoder;
import com.lagou.RpcEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class ConsumerNettyConnect {

    public static Map<String, Bootstrap> bootstrapMap = new HashMap<>();
    public static Map<String,ConsumerHandler> handlerMap = new HashMap<>();


    public void conn(String ip, int port) {
        if (bootstrapMap.get(ip + ":" + port) == null) {
            ConsumerHandler handler = new ConsumerHandler();
            //链接这台服务器
            //2)创建连接池对象
            EventLoopGroup group = new NioEventLoopGroup();
            //3)创建客户端的引导对象
            Bootstrap bootstrap = new Bootstrap();
            //4)配置启动引导对象
            bootstrap.group(group)
                    //设置通道为NIO
                    .channel(NioSocketChannel.class)
                    //设置请求协议为TCP
                    .option(ChannelOption.TCP_NODELAY, true)
                    //监听channel 并初始化
                    .handler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //获取ChannelPipeline
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //设置编码
                            pipeline.addLast(new RpcEncoder());
                            pipeline.addLast(new RpcDecoder());
                            //添加自定义事件处理器
                            pipeline.addLast(handler);
                        }
                    });
            handlerMap.put(ip+":"+port,handler);
            bootstrap.connect(ip, port);
        }else{
            Bootstrap bootstrap = bootstrapMap.get(ip + ":" + port);
            bootstrap.connect(ip, port);
        }
    }

    public void disconnect(String ip, int port) {
        String key = ip + ":" + port;
        Bootstrap bootstrap = bootstrapMap.get(ip + ":" + port);
        bootstrap.group().shutdown();
        bootstrapMap.remove(key);
        handlerMap.remove(key);
    }
}
